/**
 * 
 */
package com.xb.cloud.product.merchant.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.model.tree.TreeNode;
import com.xb.cloud.common.model.tree.TreeUtils;
import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.product.merchant.service.client.CategoryService;
import com.xb.cloud.product.merchant.service.client.bo.CategoryBo;
import com.xb.cloud.product.service.business.model.Category;
import com.xb.cloud.product.service.business.model.CategoryExample;
import com.xb.cloud.product.service.business.model.CategoryExample.Criteria;
import com.xb.cloud.product.service.business.model.mapper.CategoryMapper;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

/**
 * 后台类目服务类
 * 
 * @author kexue
 *
 */
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {

	@Resource
	private CategoryMapper categoryMapper;

	/**
	 * 根据公司id 后台类目树
	 * 
	 * @param companyId
	 *            : 公司id
	 * @param pageNum
	 *            : 分页编号
	 * @param pageSize
	 *            : 分页数据列表大小
	 */
	@Override
	public ServiceReturnInfo getCategoryBoTreeByCompanyId(long companyId) {
		
			CategoryExample categoryExample = new CategoryExample();
			Criteria criteria = categoryExample.createCriteria().andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		
			criteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
			criteria.andCompanyIdEqualTo(companyId);
			 

		 
			List<Category> categoryList = categoryMapper.selectByExample(categoryExample) ;
		 
			//通用列表转换成树形列表
			List<TreeNode<CategoryBo>> treeNodeList =convertToTreeNodeList(categoryList);
			
			//使用工具类构建树形结构
			TreeNode<CategoryBo> tree = TreeUtils.buildTree(treeNodeList);
			return ServiceReturnUtils.success(tree);
		}


		/**
		 * 将店铺内分组pojo列表，转换为通用树节点列表
		 * @param navigationGroupList
		 * @return
		 */
		private List<TreeNode<CategoryBo>> convertToTreeNodeList(List<Category> categoryList) {
			
			List<TreeNode<CategoryBo>> treeNodeList =new ArrayList<TreeNode<CategoryBo>>();
			for(Category category: categoryList){
				 TreeNode<CategoryBo> treeNode =new TreeNode<CategoryBo>();
				 treeNode.setId(category.getId()); 
				 treeNode.setCode(category.getCategoryCode()); 
				 treeNode.setIsLeaf(category.getCategoryIsLeaf()); 
				 treeNode.setName(category.getCategoryName());
				 treeNode.setParentId(category.getCategoryParentId()); 
				 treeNode.setSort(category.getCategorySort()); 
				 //额外字段
//				 treeNode.setLayerNo(category.getLayerNo());
//				 treeNode.setLayers(category.getLayers());
				 //设置data
				 treeNode.setData(BeanUtils.newAndCopyProperties(CategoryBo.class, category)); 
				 treeNodeList.add(treeNode);
			}
			return treeNodeList;
			
		}
}
